<template>
  <div class="p-2">
    <transition name="fade">
      <div v-show="showSearch" class="mb-[10px]">
        <Card>
          <Form ref="queryFormRef" :model="queryParams" layout="inline">
            <FormItem label="地域" name="region">
              <Select 
                v-model:value="queryParams.region" 
                placeholder="请选择地域" 
                allow-clear 
                style="width: 150px"
                :loading="regionLoading"
              >
                <SelectOption v-for="item in regionList" :key="item" :value="item">{{ item }}</SelectOption>
              </Select>
            </FormItem>
            <FormItem label="档位" name="grade">
              <Select 
                v-model:value="queryParams.grade" 
                placeholder="请选择档位" 
                allow-clear 
                style="width: 150px"
                :loading="gradeLoading"
              >
                <SelectOption v-for="item in gradeList" :key="item" :value="item">{{ item }}</SelectOption>
              </Select>
            </FormItem>
            <FormItem label="品牌" name="brand">
              <Select 
                v-model:value="queryParams.brand" 
                placeholder="请选择品牌" 
                allow-clear 
                style="width: 150px"
                :loading="brandLoading"
              >
                <SelectOption v-for="item in brandList" :key="item" :value="item">{{ item }}</SelectOption>
              </Select>
            </FormItem>
            <FormItem label="种类" name="category">
              <Select 
                v-model:value="queryParams.category" 
                placeholder="请选择种类" 
                allow-clear 
                style="width: 150px"
                :loading="categoryLoading"
              >
                <SelectOption v-for="item in categoryList" :key="item" :value="item">{{ item }}</SelectOption>
              </Select>
            </FormItem>
            <FormItem label="商品名称" name="productName">
              <Select 
                v-model:value="queryParams.productName" 
                placeholder="请选择商品" 
                allow-clear 
                show-search
                :filter-option="false"
                @search="handleProductSearch"
                style="width: 200px"
                :loading="productLoading"
              >
                <SelectOption v-for="item in productList" :key="item" :value="item">{{ item }}</SelectOption>
              </Select>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="handleQuery">预测</Button>
              <Button @click="resetQuery" style="margin-left: 8px">重置</Button>
            </FormItem>
          </Form>
        </Card>
      </div>
    </transition>

    <Card>
      <template #title>
        <Row :gutter="10" class="mb8" style="margin-bottom: 0">
          <Col :span="1.5">
            <Button type="default" @click="handleExport" v-access:code="['data:table:export']">导出</Button>
          </Col>
          <Col :span="1.5" style="margin-left: auto">
            <Button @click="showSearch = !showSearch">{{ showSearch ? '收起' : '展开' }}</Button>
          </Col>
        </Row>
      </template>

      <Table
        :loading="loading"
        :dataSource="tableList"
        :columns="columns"
        :pagination="false"
        :row-key="(_record: any, index?: number) => index ?? 0"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ column }">
          <template v-if="column.key === 'action'">
            <Space>
              
            </Space>
          </template>
        </template>
      </Table>

      <Pagination
        v-show="total > 0"
        :total="total"
        :current="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        show-size-changer
        :show-total="(total: number) => `共 ${total} 条`"
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
        style="margin-top: 16px; text-align: right"
      />
    </Card>

    <!-- 添加或修改数据对话框
    <Modal
      :title="dialog.title"
      v-model:open="dialog.visible"
      width="500px"
      :confirm-loading="buttonLoading"
      @ok="submitForm"
      @cancel="cancel"
    >
      <Form ref="tableFormRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <FormItem label="编号" name="dataCode">
          <Input v-model:value="form.dataCode" placeholder="请输入编号" />
        </FormItem>
        <FormItem label="表名" name="dataTable">
          <Input v-model:value="form.dataTable" placeholder="请输入表名" />
        </FormItem>
        <FormItem label="表中文名" name="dataTableName">
          <Input v-model:value="form.dataTableName" placeholder="请输入表中文名" />
        </FormItem>
        <FormItem label="SQL语句" name="dataSql">
          <Input.TextArea v-model:value="form.dataSql" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="规则公式" name="dataFormula">
          <Input.TextArea v-model:value="form.dataFormula" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="备注" name="remark">
          <Input.TextArea v-model:value="form.remark" placeholder="请输入内容" :rows="4" />
        </FormItem>
      </Form>
    </Modal> -->
  </div>
</template>

<script setup name="Table" lang="ts">
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import {
  Card,
  Form,
  FormItem,
  Button,
  Table,
  Pagination,
  Row,
  Col,
  Space,
  Select,
  SelectOption,
  message,
} from 'ant-design-vue';
import { listTable } from '#/api/operate/demandForecast/show';
import type { TableVO, TableQuery, TableForm } from '#/api/operate/demandForecast/showTypes';

const tableList = ref<TableVO[]>([]);
const allDataList = ref<TableVO[]>([]); // 存储所有数据用于客户端分页
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const regionList = ref<string[]>([]);
const regionLoading = ref(false);
const gradeList = ref<string[]>([]);
const gradeLoading = ref(false);
const brandList = ref<string[]>([]);
const brandLoading = ref(false);
const categoryList = ref<string[]>([]);
const categoryLoading = ref(false);
const productList = ref<string[]>([]);
const productLoading = ref(false);

const queryFormRef = ref();

const columns = [
  {
    title: '地域',
    dataIndex: 'md05_product_yield_area',
    key: 'md05_product_yield_area',
    align: 'center' as const,
  },
  {
    title: '档位',
    dataIndex: 'md05_product_grade_name',
    key: 'md05_product_grade_name',
    align: 'center' as const,
  },
  {
    title: '品牌',
    dataIndex: 'md05_product_brand_name',
    key: 'md05_product_brand_name',
    align: 'center' as const,
  },
  {
    title: '种类',
    dataIndex: 'md05_product_type',
    key: 'md05_product_type',
    align: 'center' as const,
  },
  {
    title: '商品代码',
    dataIndex: 'md05_product_code',
    key: 'md05_product_code',
    align: 'center' as const,
  },
  {
    title: '商品名称',
    dataIndex: 'md05_product_name',
    key: 'md05_product_name',
    align: 'center' as const,
  },
  {
    title: '订货价',
    dataIndex: 'md05_product_in_price',
    key: 'md05_product_in_price',
    align: 'center' as const,
  },
  {
    title: '销售价',
    dataIndex: 'md05_product_sale_price',
    key: 'md05_product_sale_price',
    align: 'center' as const,
  },
  {
    title: '2022_全年_销售额(元)',
    dataIndex: 'sale_price_2022',
    key: 'sale_price_2022',
    align: 'center' as const,
  },
  {
    title: '2023_全年_销售额(元)',
    dataIndex: 'sale_price_2023',
    key: 'sale_price_2023',
    align: 'center' as const,
  },
  {
    title: '2024_全年_销售额(元)',
    dataIndex: 'sale_price_2024',
    key: 'sale_price_2024',
    align: 'center' as const,
  }
];

const initFormData: TableForm = {
  md05_product_yield_area: undefined,
  md05_product_grade_name: undefined,
  md05_product_brand_name: undefined,
  md05_product_type: undefined,
  md05_product_code: undefined,
  md05_product_name: undefined,
  md05_product_in_price: undefined,
  md05_product_sale_price: undefined,
  sale_price_2022: undefined,
  sale_price_2023: undefined,
  sale_price_2024: undefined
};

const data = reactive<{
  form: TableForm;
  queryParams: TableQuery & { pageNum: number; pageSize: number; week?: string; grade?: string; brand?: string; category?: string; productName?: string };
  rules: Record<string, any[]>;
}>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dataCode: undefined,
    userId: undefined,
    param: {},
    year: undefined,
    month: undefined,
    week: undefined,
    region: undefined,
    grade: undefined,
    brand: undefined,
    category: undefined,
    productName: undefined
  },
  rules: {
    dataCode: [
      { required: true, message: "编号不能为空", trigger: "blur" }
    ],
    dataTable: [
      { required: true, message: "表名不能为空", trigger: "blur" }
    ],
    dataTableName: [
      { required: true, message: "表中文名不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams } = toRefs(data);

/** 更新表格显示数据(客户端分页) */
const updateTableList = () => {
  const startIndex = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
  const endIndex = startIndex + queryParams.value.pageSize;
  tableList.value = allDataList.value.slice(startIndex, endIndex);
};

/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listTable(queryParams.value);
    console.log('API 返回数据:', res);
    
    // 根据后端实际返回的数据结构处理
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      // 如果直接返回数组
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      // 如果返回的是 { rows: [...], total: number } 结构
      dataList = res.rows;
    } else {
      console.warn('未知的数据结构:', res);
      dataList = [];
    }
    
    // 根据条件筛选数据
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => 
        item.md05_product_yield_area === queryParams.value.region
      );
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => 
        item.md05_product_grade_name === queryParams.value.grade
      );
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => 
        item.md05_product_brand_name === queryParams.value.brand
      );
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => 
        item.md05_product_type === queryParams.value.category
      );
    }
    if (queryParams.value.productName) {
      dataList = dataList.filter((item: any) => 
        item.md05_product_name === queryParams.value.productName
      );
    }
    
    // 按档位顺序排序
    const gradeOrder = ['一档', '二档', '三档', '四档', '五档', '六档', '七档', '八档', '九档', '十档'];
    dataList.sort((a: any, b: any) => {
      const gradeA = a.md05_product_grade_name || '';
      const gradeB = b.md05_product_grade_name || '';
      const indexA = gradeOrder.indexOf(gradeA);
      const indexB = gradeOrder.indexOf(gradeB);
      
      // 如果都在预定义列表中,按预定义顺序排序
      if (indexA !== -1 && indexB !== -1) {
        return indexA - indexB;
      }
      // 如果只有一个在预定义列表中,在列表中的排前面
      if (indexA !== -1) return -1;
      if (indexB !== -1) return 1;
      // 如果都不在预定义列表中,按字母顺序排序
      return gradeA.localeCompare(gradeB, 'zh-CN');
    });
    
    // 保存全量数据用于分页
    allDataList.value = dataList;
    total.value = dataList.length;
    
    // 客户端分页
    updateTableList();
    
    console.log('处理后的表格数据:', tableList.value);
    console.log('数据总数:', total.value);
  } catch (error) {
    console.error('获取数据失败:', error);
    tableList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 导出按钮操作 */
const handleExport = async () => {
  // 构建筛选条件提示
  const conditions: string[] = [];
  if (queryParams.value.region) conditions.push(`地域:${queryParams.value.region}`);
  if (queryParams.value.grade) conditions.push(`档位:${queryParams.value.grade}`);
  if (queryParams.value.brand) conditions.push(`品牌:${queryParams.value.brand}`);
  if (queryParams.value.category) conditions.push(`种类:${queryParams.value.category}`);
  if (queryParams.value.productName) conditions.push(`商品:${queryParams.value.productName}`);
  
  const conditionText = conditions.length > 0 ? `(筛选条件: ${conditions.join(', ')})` : '(全部数据)';
  const hideLoading = message.loading(`正在导出数据${conditionText}...`, 0);
  
  try {
    // 获取当前筛选后的数据
    const res = await listTable(queryParams.value);
    
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    // 根据条件筛选数据
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.md05_product_yield_area === queryParams.value.region);
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => item.md05_product_grade_name === queryParams.value.grade);
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => item.md05_product_brand_name === queryParams.value.brand);
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => item.md05_product_type === queryParams.value.category);
    }
    if (queryParams.value.productName) {
      dataList = dataList.filter((item: any) => item.md05_product_name === queryParams.value.productName);
    }
    
    // 检查是否有数据
    if (dataList.length === 0) {
      message.warning('当前筛选条件下没有数据可导出');
      return;
    }
    
    // 按档位顺序排序
    const gradeOrder = ['一档', '二档', '三档', '四档', '五档', '六档', '七档', '八档', '九档', '十档'];
    dataList.sort((a: any, b: any) => {
      const gradeA = a.md05_product_grade_name || '';
      const gradeB = b.md05_product_grade_name || '';
      const indexA = gradeOrder.indexOf(gradeA);
      const indexB = gradeOrder.indexOf(gradeB);
      
      if (indexA !== -1 && indexB !== -1) {
        return indexA - indexB;
      }
      if (indexA !== -1) return -1;
      if (indexB !== -1) return 1;
      return gradeA.localeCompare(gradeB, 'zh-CN');
    });
    
    // 转换为CSV格式
    const headers = ['地域', '档位', '品牌', '种类', '商品代码', '商品名称', '订货价', '销售价', '2022_全年_销售额(元)', '2023_全年_销售额(元)', '2024_全年_销售额(元)'];
    const csvContent = [
      headers.join(','),
      ...dataList.map((item: any) => [
        item.md05_product_yield_area || '',
        item.md05_product_grade_name || '',
        item.md05_product_brand_name || '',
        item.md05_product_type || '',
        item.md05_product_code || '',
        item.md05_product_name || '',
        item.md05_product_in_price || '',
        item.md05_product_sale_price || '',
        item.sale_price_2022 || '',
        item.sale_price_2023 || '',
        item.sale_price_2024 || ''
      ].join(','))
    ].join('\n');
    
    // 添加BOM头以支持中文
    const BOM = '\uFEFF';
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
    
    // 构建文件名
    let fileName = '年度需求销售额';
    if (queryParams.value.region) fileName += `_${queryParams.value.region}`;
    if (queryParams.value.grade) fileName += `_${queryParams.value.grade}`;
    if (queryParams.value.brand) fileName += `_${queryParams.value.brand}`;
    fileName += `_${new Date().getTime()}.csv`;
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', fileName);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    message.success(`导出成功! 共导出 ${dataList.length} 条数据`);
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败');
  } finally {
    hideLoading();
  }
};

/** 分页变化 */
const handlePageChange = (page: number) => {
  queryParams.value.pageNum = page;
  updateTableList(); // 使用客户端分页,无需重新请求
};

/** 分页大小变化 */
const handlePageSizeChange = (_current: number, size: number) => {
  queryParams.value.pageSize = size;
  queryParams.value.pageNum = 1;
  updateTableList(); // 使用客户端分页,无需重新请求
};

/** 获取地域列表 */
const getRegionList = async () => {
  regionLoading.value = true;
  try {
    const res = await listTable({
      dataCode: 'MonthlySales_year_price',
      userId: '123',
      param: ''
    });
    
    // 从返回的数据中提取唯一的地域列表
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    // 提取唯一的地域值
    const regions = new Set<string>();
    dataList.forEach((item: any) => {
      if (item.md05_product_yield_area) {
        regions.add(item.md05_product_yield_area);
      }
    });
    
    regionList.value = Array.from(regions).sort();
  } catch (error) {
    console.error('获取地域列表失败:', error);
    message.error('获取地域列表失败');
  } finally {
    regionLoading.value = false;
  }
};

/** 获取档位列表 */
const getGradeList = async () => {
  gradeLoading.value = true;
  try {
    const res = await listTable({
      dataCode: 'MonthlySales_year_price',
      userId: '123',
      param: ''
    });
    
    // 从返回的数据中提取唯一的档位列表
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    // 根据已选条件筛选数据
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.md05_product_yield_area === queryParams.value.region);
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => item.md05_product_brand_name === queryParams.value.brand);
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => item.md05_product_type === queryParams.value.category);
    }
    
    // 提取唯一的档位值
    const grades = new Set<string>();
    dataList.forEach((item: any) => {
      if (item.md05_product_grade_name) {
        grades.add(item.md05_product_grade_name);
      }
    });
    
    // 自定义排序:按档位顺序(一档、二档、三档...)
    const gradeOrder = ['一档', '二档', '三档', '四档', '五档', '六档', '七档', '八档', '九档', '十档'];
    gradeList.value = Array.from(grades).sort((a, b) => {
      const indexA = gradeOrder.indexOf(a);
      const indexB = gradeOrder.indexOf(b);
      // 如果都在预定义列表中,按预定义顺序排序
      if (indexA !== -1 && indexB !== -1) {
        return indexA - indexB;
      }
      // 如果只有一个在预定义列表中,在列表中的排前面
      if (indexA !== -1) return -1;
      if (indexB !== -1) return 1;
      // 如果都不在预定义列表中,按字母顺序排序
      return a.localeCompare(b, 'zh-CN');
    });
  } catch (error) {
    console.error('获取档位列表失败:', error);
    message.error('获取档位列表失败');
  } finally {
    gradeLoading.value = false;
  }
};

/** 获取品牌列表 */
const getBrandList = async () => {
  brandLoading.value = true;
  try {
    const res = await listTable({
      dataCode: 'MonthlySales_year_price',
      userId: '123',
      param: ''
    });
    
    // 从返回的数据中提取唯一的品牌列表
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    // 根据已选条件筛选数据
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.md05_product_yield_area === queryParams.value.region);
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => item.md05_product_grade_name === queryParams.value.grade);
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => item.md05_product_type === queryParams.value.category);
    }
    
    // 提取唯一的品牌值
    const brands = new Set<string>();
    dataList.forEach((item: any) => {
      if (item.md05_product_brand_name) {
        brands.add(item.md05_product_brand_name);
      }
    });
    
    brandList.value = Array.from(brands).sort();
  } catch (error) {
    console.error('获取品牌列表失败:', error);
    message.error('获取品牌列表失败');
  } finally {
    brandLoading.value = false;
  }
};

/** 获取种类列表 */
const getCategoryList = async () => {
  categoryLoading.value = true;
  try {
    const res = await listTable({
      dataCode: 'MonthlySales_year_price',
      userId: '123',
      param: ''
    });
    
    // 从返回的数据中提取唯一的种类列表
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    // 根据已选条件筛选数据
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.md05_product_yield_area === queryParams.value.region);
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => item.md05_product_grade_name === queryParams.value.grade);
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => item.md05_product_brand_name === queryParams.value.brand);
    }
    
    // 提取唯一的种类值
    const categories = new Set<string>();
    dataList.forEach((item: any) => {
      if (item.md05_product_type) {
        categories.add(item.md05_product_type);
      }
    });
    
    categoryList.value = Array.from(categories).sort();
  } catch (error) {
    console.error('获取种类列表失败:', error);
    message.error('获取种类列表失败');
  } finally {
    categoryLoading.value = false;
  }
};

/** 获取商品列表 */
const getProductList = async () => {
  productLoading.value = true;
  try {
    const res = await listTable({
      dataCode: 'MonthlySales_year_price',
      userId: '123',
      param: ''
    });
    
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.md05_product_yield_area === queryParams.value.region);
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => item.md05_product_grade_name === queryParams.value.grade);
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => item.md05_product_brand_name === queryParams.value.brand);
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => item.md05_product_type === queryParams.value.category);
    }
    
    const products = new Set<string>();
    dataList.forEach((item: any) => {
      if (item.md05_product_name) {
        products.add(item.md05_product_name);
      }
    });
    
    productList.value = Array.from(products).sort();
  } catch (error) {
    console.error('获取商品列表失败:', error);
  } finally {
    productLoading.value = false;
  }
};

/** 商品搜索 */
const handleProductSearch = async (keyword: string) => {
  if (!keyword) {
    await getProductList();
    return;
  }
  
  productLoading.value = true;
  try {
    const res = await listTable({
      dataCode: 'MonthlySales_year_price',
      userId: '123',
      param: ''
    });
    
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    if (queryParams.value.region) {
      dataList = dataList.filter((item: any) => item.md05_product_yield_area === queryParams.value.region);
    }
    if (queryParams.value.grade) {
      dataList = dataList.filter((item: any) => item.md05_product_grade_name === queryParams.value.grade);
    }
    if (queryParams.value.brand) {
      dataList = dataList.filter((item: any) => item.md05_product_brand_name === queryParams.value.brand);
    }
    if (queryParams.value.category) {
      dataList = dataList.filter((item: any) => item.md05_product_type === queryParams.value.category);
    }
    
    const products = new Set<string>();
    dataList.forEach((item: any) => {
      if (item.md05_product_name && item.md05_product_name.includes(keyword)) {
        products.add(item.md05_product_name);
      }
    });
    
    productList.value = Array.from(products).sort();
  } catch (error) {
    console.error('搜索商品失败:', error);
  } finally {
    productLoading.value = false;
  }
};

// 监听搜索条件变化,实现联动筛选
watch(
  () => [queryParams.value.region, queryParams.value.grade, queryParams.value.brand, queryParams.value.category],
  () => {
    // 当任一条件变化时,重新加载其他选择框的数据
    getGradeList();
    getBrandList();
    getCategoryList();
  },
  { deep: true }
);

onMounted(() => {
  getRegionList();
  getGradeList();
  getBrandList();
  getCategoryList();
  getProductList();
  getList();
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
